var fs = require('fs');
var path = require('path');
var utils = require('./utils');

function send(request, response, file) {
  if (file == undefined) {
    response.end();
    return;
  }

  console.log('Downloading ' + file);
  response.setHeader('Content-type', 'binary');
  response.setHeader('Content-disposition', 'attachment; filename=' + file);

  while (!path.existsSync(file)) {
    console.log('sleeping 50 ms.');
    utils.sleep(50);
  }

  var file_stream = fs.createReadStream(file);
  
  file_stream.on('data', function(chunk) {
    response.write(chunk);
  });
  
  file_stream.on('close', function() {
    response.end();
  });
}

exports.send = send;
